//
//  WDTabBar.swift
//  SINAWeiBo
//
//  Created by wangwei on 2016/11/12.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

class WDTabBar: UITabBar {

    //声明一个闭包
    var composeClick: (() -> ())?
    
    
    //懒加载button 中间的那个按钮
    lazy var composeBtn: UIButton = { () -> UIButton in
    
        let btn = UIButton(type: UIButtonType.custom)
        
        //这里我们需要设置btn 的图片,貌似是没有文字的
        btn.setImage(#imageLiteral(resourceName: "tabbar_compose_icon_add"), for: UIControlState.normal)
        btn.setImage(#imageLiteral(resourceName: "tabbar_compose_icon_add_highlighted"), for: UIControlState.highlighted)
        
        btn.setBackgroundImage(#imageLiteral(resourceName: "tabbar_compose_button"), for: UIControlState.normal)
        btn.setBackgroundImage(#imageLiteral(resourceName: "tabbar_compose_button_highlighted"), for: UIControlState.highlighted)
        
        //设置大小尺寸
        btn.sizeToFit()
        
        
        return btn
    }()
 
    override init(frame: CGRect) {
        super.init(frame: frame)
        //在这个代码中,我们需要添加中间的那个button
        addSubview(composeBtn)
        
        //给composeBtn 添加监听方法
        composeBtn.addTarget(self, action: #selector(composeBtnClick), for: .touchUpInside)
        
    }
    @objc private  func composeBtnClick() {
    
       //执行闭包
        composeClick?()
    
    }
    
    
    //当你重写系统的构造方法后,会会出现这段代码
    required init?(coder aDecoder: NSCoder) {
        //fatalError("init(coder:) has not been implemented")
        super.init(coder: aDecoder)
        self.addSubview(composeBtn)
    }
    
    //排布子控件
    override func layoutSubviews() {
        super.layoutSubviews()
        //现在我们要做的就是遍历得到TabBar上面的每一个子控件,给子空间上面的
        
        let w = self.bounds.width/5.0
        let h = self.bounds.height
        var index: CGFloat = 0
        
        for subView in subviews {
            
            if subView.isKind(of: NSClassFromString("UITabBarButton")!) {
                
                //修改frame
                subView.frame = CGRect(x: index * w, y: 0, width: w, height: h)
                
                index += (index == 1 ? 2 : 1)
            
            }
        }
        
        //现在我们需要做的是设置composeBtn的frame
        composeBtn.center = CGPoint(x:self.center.x , y: h * 0.5)
        
        
        
        
    }

}
